package com.czzn.czkongzhi;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.TextView;

import java.math.BigDecimal;

public class RockerActivity extends FunctionActivity implements View.OnClickListener{

    private MySurfaceView mySurfaceView;
    public static boolean isGra=false;
    private TextView textView,send,k;
    public static final int UPDATE_TEXT=1;
    int t1,t2;
    int left,right;
    String PWM1,PWM2,changeData="E8A300",changeData2="E8A400";
    double k3,k4;
    Button button1,button2,button3,button4,button5;
    public int isLeftGoForward=1,isLeftGo=2;
    public int isRightGoForward=3,isRightGo=4;
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        setContentView(R.layout.activity_control);
        init();
        calculate();
    }

    private void init(){
        mySurfaceView =findViewById(R.id.control);
        button1=findViewById(R.id.open);
        button2=findViewById(R.id.close);
        button3=findViewById(R.id.pwm);
        button4=findViewById(R.id.IO);
        button1.setOnClickListener(this);
        button2.setOnClickListener(this);
        button3.setOnClickListener(this);
        button4.setOnClickListener(this);
        textView=findViewById(R.id.zhankongbi);
        send=findViewById(R.id.send);
        k=findViewById(R.id.k3);
    }

    private void calculate(){
        mySurfaceView.setOnDownActionListener(new MySurfaceView.OnDownActionListener() {
            @Override
            public void onDown(int x, int y ) {
                //x像素坐标为960，y像素坐标为400
                int a=x-960;
                int b=-(y-400);
                //计算左轮
                calculateLeft(a,b);
                calculateRight(a,b);
                //对左轮进行高低电平判断，当isLeftGoForward为1，为低电平；当isLeftGoForward为2，则为高电平
                if (b>0&&a+b>0){
                    isLeftGoForward=2;
                }else if (b>0&&a+b<0){
                    isLeftGoForward=1;
                }else if (b<0&&b-a<0){
                    isLeftGoForward=1;
                }else if (b<0&&b-a>0){
                    isLeftGoForward=2;
                }
                if (isLeftGoForward!=isLeftGo){
                    if (isLeftGoForward==1){
                        try {
                            String IO1 = "E7F300";
                            byte[] high1 = stringToBytes(IO1);
                            beuse.send(high1);
                            Log.i("send", "开启低电频.IO1=" + IO1);
                        } catch (Exception e) {
                            Log.e("Error", "Bluetooth is null");
                        }
                    }else if (isLeftGoForward==2){
                        Log.i("ce1234", "开启左高电频.");
                        try {
                            String IO1 = "E7F301";
                            byte[] high1 = stringToBytes(IO1);
                            beuse.send(high1);
                            Log.i("send", "开启高电频.IO1=" + IO1);
                        } catch (Exception e) {
                            Log.e("Error", "Bluetooth is null");
                        }
                    }
                    isLeftGo=isLeftGoForward;
                }

                //对右轮进行高低电平判断，当isRightGoForward为3，为低电平；当isGoForward为4，则为高电平
                if (b>0&&b-a>0){
                    isRightGoForward=4;
                }else if (b>0&&b-a<0){
                    isRightGoForward=3;
                }else if (b<0&&a+b<0){
                    isRightGoForward=3;
                }else if (b<0&&a+b>0){
                    isRightGoForward=4;
                }
                if (isRightGoForward!=isRightGo){
                    if (isRightGoForward==3){
                        Log.i("ce1234", "开启右低电频.");
                        try {
                            String IO2 = "E7F200";
                            byte[] high2 = stringToBytes(IO2);
                            beuse.send(high2);
                            Log.i("send", "开启低电频.IO2=" + IO2);
                        } catch (Exception e) {
                            Log.e("Error", "Bluetooth is null");
                        }
                    }else if (isRightGoForward==4){
                        Log.i("ce1234", "开启右高电频.");
                        try {
                            String IO2 = "E7F201";
                            byte[] high2 = stringToBytes(IO2);
                            beuse.send(high2);
                            Log.i("send", "开启高电频.IO2=" + IO2);
                        } catch (Exception e) {
                            Log.e("Error", "Bluetooth is null");
                        }
                    }
                    isRightGo=isRightGoForward;
                }
            }
        });
        mySurfaceView.setOnUpActionListener(new MySurfaceView.OnUpActionListener() {
            @Override
            public void OnUp(int x, int y) {
                String Up="E8A400";
                byte[] send=stringToBytes(Up);
                try {
                    beuse.send(send);
                }catch (Exception e){
                    Log.e("Error","蓝牙为空");
                }
                Log.e("Up","x:"+x+",y:"+y);
            }
        });
    }

    private void calculateLeft(int a,int b ){
        //计算左轮
        if (b>0) {
            left = a + b;
        }else {
            left=b-a;
        }
            if (left < 0) {
                left = -left;
            }
            //计算占空比
            double k1 = left / 350.0;
            //保留2位小数
            BigDecimal bg = new BigDecimal(k1);
            k3 = bg.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
            //定义PWM2的前四位
            String PWM_Prefix = "E8A3";
            //占空比值最大为255,这里设置为100
            t1 = (int) (100 * k3);
            String a1 = Integer.toHexString(t1);
            if (a1.length() == 1) {
                PWM1 = PWM_Prefix + "0" + a1;
            } else {
                PWM1 = PWM_Prefix + a1;
            }
            Log.e("TAG", "left=" + left + ",+k1=" + k1);
            Log.e("TAG", "PWM1=" + PWM1);
            /**
             * 判断是否改变速度
             */
            if (PWM1.equals(changeData)) {
                Log.e("TRY", "no send because PMW1=" + PWM1);
            } else {
                byte[] send = stringToBytes(PWM1);
                try {
                    beuse.send(send);
                    Log.e("send", "send" + PWM1 + ",send2" + changeData);
                } catch (Exception e) {
                    Log.e("Error", "蓝牙为空");
                }
                changeData = PWM1;
                Log.e("TRY", "send yes!because PMW1=" + PWM1 + ",PWM2=" + changeData);
            }
            Log.d("TAG", "PWM1" + PWM1);
            Log.d("TAG", "k3" + k3);
            Log.d("TAG", "t1" + t1);
            /**
             * 更新线程，测试专用，后期删除
             */
            new Thread(new Runnable() {
                @Override
                public void run() {
                    Message message = new Message();
                    message.what = UPDATE_TEXT;
                    handler.sendMessage(message);
                }
            }).start();
        }

    private void calculateRight(int a,int b){
        //计算右轮
        if (b>0) {
            right = b - a;
        }else {
            right=a+b;
        }
        if (right<0){
            right=-right;
        }
        //计算占空比
        double k2=right/350.0;
        //保留2位小数
        BigDecimal bg = new BigDecimal(k2);
        k4 = bg.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();

        //定义PWM2的前四位
        String PWM_Prefix="E8A4";
        t2= (int) (100*k4);
        String a2=Integer.toHexString(t2);
        if (a2.length()==1){
            PWM2=PWM_Prefix+"0"+a2;
        }else {
            PWM2=PWM_Prefix+a2;
        }

        /**
         * 判断是否改变速度
         */
        if (PWM2.equals(changeData2)){
            Log.e("Right","no send because PMW2="+PWM2);
        }
        else {
            byte[] send=stringToBytes(PWM2);
            try {
                beuse.send(send);
                Log.e("Right","send"+PWM2+",send2"+changeData2);
            }catch (Exception e){
                Log.e("Error","蓝牙为空");
            }
            changeData2=PWM2;
            Log.e("Right","send yes!because PMW1="+PWM2+",PWM2="+changeData2);
        }
    }

    @Override
    public void onResume(){
        super.onResume();
    }
    @Override
    public void onPause(){
        super.onPause();
    }

    private byte[] stringToBytes(String s) {
        byte[] buf = new byte[s.length() / 2];
        for (int i = 0; i < buf.length; i++) {
            try {
                buf[i] = (byte) Integer.parseInt(s.substring(i * 2, i * 2 + 2), 16);
            } catch (NumberFormatException e) {
                e.printStackTrace();
            }
        }
        return buf;
    }

    /**
     * 更新UI线程
     */
    public Handler handler =new Handler(){

        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                case UPDATE_TEXT:
                    textView.setText("相对数值："+left);
                    send.setText("A指令："+PWM1);
                    k.setText("A占空比："+k3*100+"%");
                    break;
                default:
                    break;
            }
        }
    };

    @Override
    public void onClick(View view) {
        byte[] PTL1;
        byte[] PTL2;
        switch (view.getId()){
            case R.id.open:
                String open1="E8A419";
                String open2="E7F401";
                PTL1=stringToBytes(open1);
                PTL2=stringToBytes(open2);
                beuse.send(PTL1);
                //beuse.send(PTL2);
                break;
            case R.id.close:
                String close1="E8A47D";
                String close2="E7F400";
                PTL1=stringToBytes(close1);
                PTL2=stringToBytes(close2);
                beuse.send(PTL1);
                //beuse.send(PTL2);
                break;
            case R.id.pwm:
                String pwm="E7F400";
                PTL1=stringToBytes(pwm);
                beuse.send(PTL1);
                break;
            case R.id.IO:
                String IO="E8A203E8";
                PTL1=stringToBytes(IO);
                beuse.send(PTL1);
            default:
                break;
        }
    }
}
